Imports System.Collections
Imports System.Web.UI.WebControls
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Imports Cdm
Imports Cdm.DataCore
Imports Cdm.AppServices
Imports Cdm.AppServices.Log
Partial Class Reports_ReportViewerParticipant
    Inherits System.Web.UI.Page

#Region "CONSTANTS"
    Private Const _CLASS_NAME As String = "Reports_ReportViewerParticipant"
    'Private Const _SERVER_NAME = "10.1.2.12"
    Private Const ReportFileName As String = "ParticipantDetails.rpt"
#End Region

#Region "PRIVATE MEMBERS"

    Private reportDocument As CrystalDecisions.CrystalReports.Engine.ReportDocument
    Private parameterList As ArrayList

#End Region

#Region "PRIVATE METHODS"
    
    Private Sub SetCurrentValuesForParameterField(ByVal reportDocument As ReportDocument, ByVal paramName As String, ByVal value As Object)
        Try

            Dim params As ParameterValues = New ParameterValues()
            Dim paramsDiscreteValues As ParameterDiscreteValue = New ParameterDiscreteValue()
            paramsDiscreteValues.Value = value.ToString()
            params.Add(paramsDiscreteValues)

            reportDocument.DataDefinition.ParameterFields.Item(paramName).ApplyCurrentValues(params)

            If Not reportDocument.IsSubreport Then
                Me.ReportViewer.ParameterFieldInfo.Item(paramName).CurrentValues = reportDocument.ParameterFields.Item(paramName).CurrentValues
            End If

        Catch ex As Exception
            Log.ErrorLog(_CLASS_NAME, "An error occurred in the SetCurrentValuesForParameterField() method.", ex)
            Throw ex
        End Try
    End Sub

    Private Function ApplyLogon(ByVal reportDocument As CrystalDecisions.CrystalReports.Engine.ReportDocument, ByVal conn As CrystalDecisions.Shared.ConnectionInfo) As Boolean
        ' This function is called by the "Logon" function
        ' It loops through the report tables and applies
        ' the connection information to each table.

        Try

            ' Declare the TableLogOnInfo object and a table object for use later.
            Dim tableLogonInfo As CrystalDecisions.Shared.TableLogOnInfo
            Dim table As CrystalDecisions.CrystalReports.Engine.Table

            ' For each table apply connection info.
            For Each table In reportDocument.Database.Tables
                tableLogonInfo = table.LogOnInfo
                tableLogonInfo.ConnectionInfo = conn
                table.ApplyLogOnInfo(tableLogonInfo)

                ' Verify that the logon was successful.
                ' If TestConnectivity returns false, correct table locations.
                If (table.TestConnectivity()) Then
                    ' If there is a "." in the location then remove the
                    ' beginning of the fully qualified location.
                    ' Example "dbo.northwind.customers" would become
                    ' "customers".
                    If (table.Location.IndexOf(".") > 0) Then
                        table.Location = table.Location.Substring(table.Location.LastIndexOf(".") + 1)
                    Else
                        ' If the location is not returning as a fully
                        ' qualified location we still set it to table.location
                        ' because Crystal Reports 9 installed on top of .NET
                        ' can *store* fully qualified names but will only *return*
                        ' the table name itself.
                        table.Location = table.Location
                    End If
                Else
                    Return False
                End If
            Next

            Return True

        Catch ex As Exception
            Log.ErrorLog(_CLASS_NAME, "An error occurred in the ApplyLogon() method.", ex)
        End Try
    End Function

    ' The Logon method iterates through all tables.
    Private Function Logon(ByVal reportDocument As CrystalDecisions.CrystalReports.Engine.ReportDocument, _
        ByVal server As String, _
        ByVal database As String, _
        ByVal user_id As String, _
        ByVal password As String) As Boolean

        Try

            ' Declare and populate a new connection info object.
            Dim conn As New CrystalDecisions.Shared.ConnectionInfo()
            'Dim connItems As Array = ConfigurationManager.ConnectionStrings("SpendingPlanData").ToString().Split(";")
            Dim connItems As Array = EntityController.AppConnectString().Split(";")
            Dim connAttributes As New NameValueCollection
            For Each str As String In connItems
                If str.Trim().Length > 0 Then
                    Dim pair() As String
                    pair = str.Split("=")
                    connAttributes.Add(pair(0), pair(1))
                End If
            Next

            With conn
                .ServerName = server
                .DatabaseName = database
                .UserID = user_id
                .Password = password
            End With

            ' If the ApplyLogon function fails then return a false for this function.
            ' We are applying logon information to the main report at this stage.
            If (Not ApplyLogon(reportDocument, conn)) Then
                Return False
            End If

            ' Declare both a report object as well as a subreport object.
            Dim reportObject As CrystalDecisions.CrystalReports.Engine.ReportObject
            Dim subreportObject As CrystalDecisions.CrystalReports.Engine.SubreportObject

            ' Loop through all the report objects and locate subreports.
            ' If a subreport is found then apply logon information to
            ' the subreport.
            For Each reportObject In reportDocument.ReportDefinition.ReportObjects
                If (reportObject.Kind = CrystalDecisions.[Shared].ReportObjectKind.SubreportObject) Then
                    subreportObject = CType(reportObject, CrystalDecisions.CrystalReports.Engine.SubreportObject)
                    If (Not ApplyLogon(reportDocument.OpenSubreport(subreportObject.SubreportName), conn)) Then
                        Return False
                    End If
                End If
            Next

            ' Return True if the code runs to this stage.
            Return True

        Catch ex As Exception
            Log.ErrorLog(_CLASS_NAME, "An error occurred in the SetParameters() method.", ex)
            Throw ex
        End Try

    End Function

    Private Sub ConfigureCrystalReports()
        Try

            Dim paramList As ArrayList = New ArrayList()
            Dim reportPath As String = Server.MapPath(ReportFileName)

            Me.reportDocument = New ReportDocument()
            Me.reportDocument.Load(reportPath)

            Dim connItems As Array = EntityController.AppConnectString.Split(";")
            Dim connAttributes As New NameValueCollection
            For Each str As String In connItems
                If str.Trim().Length > 0 Then
                    Dim pair() As String
                    pair = str.Split("=")
                    connAttributes.Add(pair(0), pair(1))
                End If
            Next

            Me.reportDocument.SetDatabaseLogon(connAttributes("User ID"), connAttributes("Password"), connAttributes("Data Source"), connAttributes("Initial Catalog"))
            If Me.Logon(Me.reportDocument, connAttributes("Data Source"), connAttributes("Initial Catalog"), connAttributes("User ID"), connAttributes("Password")) Then

                ReportViewer.ReportSource = reportDocument

                Me.SetParameters()

            End If

        Catch ex As Exception
            Log.ErrorLog(_CLASS_NAME, "An error occurred in the ConfigureCrystalReports() method.", ex)
            Throw ex
        End Try
    End Sub

    Private Sub SetParameters()
        Try
            Me.SetCurrentValuesForParameterField(Me.reportDocument, "@participantId", EntityController.GetParticipant().ParticipantId)
           
        Catch ex As Exception
            Log.ErrorLog(_CLASS_NAME, "An error occurred in the SetParameters() method.", ex)
            Throw ex
        End Try
    End Sub

    
    

#End Region

#Region "EVENT HANDLERS"

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Try
            Me.ConfigureCrystalReports()

        Catch ex As Exception
            Log.ErrorLog(_CLASS_NAME, "An error occurred in the Page_Load() method.", ex)
        End Try

    End Sub

#End Region


    Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
        Me.ReportViewer.Dispose()
    End Sub
End Class
